import config from "../config.js"
import Cache from "../cache.js"
import Loading from "../loading.js"

const REFRESH_URL = '/token/refresh';


let isRefreshing = false;
let RequestStack = [];

export const getHeader = ()=>{
	let header = {
		"Content-Type": "application/x-www-form-urlencoded",
		
	}
	let token = ''
	if(Cache.cache.get('token')){
		token = Cache.cache.get('token')
	}else{
		// token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJORlQiLCJhdWQiOiIiLCJpYXQiOjE2OTY4Mzc1MTgsIm5iZiI6MTY5NjgzNzUxOCwiZXhwIjo0ODUwNDM3NTE4LCJ1aWQiOjM4OH0.7lKrn2rlu_EcRIVzdFQXhGf0QEM0zBSCrdZueUlP2t8"
		// Cache.cache.set('token',token)
	}
	
	header['token'] = `${token}`;
	
	
	return header;
}

export const showToast = (title)=>{
	// uni.hideLoading();
	setTimeout( () => {
	  uni.showToast({
	    title: title,
	    icon: "none",
	  });
	  setTimeout( () =>{
	    uni.hideToast();  
	  },2000)
	},0);
}
export const request = (url,method,data,header,loading)=>{
	return new Promise((resolved, rejected) => {
		if(loading){
			Loading.showLoading();
		}
		// if(header.token.length==0){
		// 	Loading.hideLoading()
		// 	console.log('没token')
		// 	return rejected('未登录')
		// }
		uni.request({
			url:`${config.baseUrl}${url}`,
			data:data,
			header:header,
			method:method,
			success(res) {
				let resData = res.data;
				if(resData.code == 200){
					return resolved(resData.data);
				}else {
					//业务错误
					console.log(90,resData.message)
					if(resData.message!='登录失败'){
						showToast(resData.message);
					}
					return rejected(res);
				} 
			},
			fail(err) {
				//网络错误
				showToast('网络错误');
				return rejected(err);
			},
			complete(res) {
				if(loading){
					Loading.hideLoading();
				}
			}
		})
	});
}


export const POST = (url,data,loading = true)=>{
	return request(url,"POST",data,getHeader(),loading);
};

export const POSTNOLOADING = (url,data,loading = false)=>{
	return request(url,"POST",data,getHeader(),loading);
};

export const POSTJSON = (url,data,loading = true)=>{
	let header = getHeader(); 
	header['Content-Type'] = 'application/json';
	return request(url,"POST",data,header,loading);
};

export const GET = (url,data,loading = true)=>{
	return request(url,"POST",data,getHeader(),loading);
};


